import { Toast } from "antd-mobile";
import { useCallback, useEffect, useRef, useState } from "react"
import Hammer from "hammerjs";
const touchEle = []
function calculateOverlapArea(rect1, rect2) {
    const xOverlap = Math.max(0, Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left));
    const yOverlap = Math.max(0, Math.min(rect1.bottom, rect2.bottom) - Math.max(rect1.top, rect2.top));
    return xOverlap * yOverlap;
  }
export const useGameV2 = (count = 12,options) => {
    const numRows = 4;
    const numCols = 3;
    let posX = 0
    let posY = 0
    const imgArr = useRef([])
    const lis = useRef([])
    const canvasRef = useRef()
    const imgBoxRef = useRef()
    const event = useRef(0)
    const randomImg = () => {
        for (let index = 0; index < count; index++) {
            const li = document.createElement('div')
            li.classList.add('gridItem')
            const img = new Image()
            img.classList.add('canvas-img')
            img.style.display = 'block'
            const hammer = new Hammer.Manager(img)
            // 启用所需的手势识别器
const pan = new Hammer.Pan();
// const pinch = new Hammer.Pinch();
hammer.add([pan]);
hammer.get('pan').set({ enable: true });
// hammer.get('pinch').set({ enable: false });
            // hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL })
            // 监听拖动事件
            hammer.on('panstart', function (e) {
                const target = e.target.closest('.gridItem')
                posX = target.offsetLeft;
                posY = target.offsetTop;
                if(e.target.classList.contains('disabled')) {
                    lis.current.forEach(li => {
                        li.style.left = li.getAttribute('prevLeft') + 'px'
                        li.style.top = li.getAttribute('prevTop') + 'px'
                    })
                    return
                }
                const imgs = imgBoxRef.current.querySelectorAll('img')
                // console.log(e.target)
                imgs.forEach(i => {
                    console.log(i,e.target)
                    if (i!==e.target) {
                        i.classList.add('disabled')
                    }
                })
                if (imgBoxRef.current.classList.contains('disabled')) return
                if (event.current>1) {
                    const imgs = imgBoxRef.current.querySelectorAll('img')
                    return
                }
                // 当拖动开始时，保存当前元素的位置
                // if (event.current.length>1) return
                // console.log(li.offsetLeft)
               
                target.style.zIndex = 1
                
                
                
                // target.setAttribute('prevLeft', posX)
                // target.setAttribute('prevTop', posY)
                // console.log(posX,posY)
            });

            hammer.on('pan', function (e) {
                // console.log('panssdsd', e.target.tagName)
                // 计算元素新的位置
                if (imgBoxRef.current.classList.contains('disabled')) return
                if (event.current>1) return
                
                const targetElement = e.target.closest('.gridItem')
                const { left: containerLeft, right: containerRight, top: containerTop, bottom: containerBottom } = imgBoxRef.current.getBoundingClientRect()
                // console.log(containerLeft,containerRight)
                let deltaX = posX + e.deltaX;
                let deltaY = posY + e.deltaY;
                // 限制元素的拖动范围在容器边界内
                const num = window.innerWidth>=414?348:320
                const containerScrollLeft = window.innerWidth - num;
                // alert(window.innerWidth)
                const containerScrollTop = imgBoxRef.current.offsetTop + window.innerHeight*0.29;
                console.log(containerScrollTop)
                // Calculate the boundary coordinates
                const minX = containerLeft - containerScrollLeft+20;
                const maxX = containerRight - containerScrollLeft - targetElement.offsetWidth+22;
                const minY = containerTop - containerScrollTop;
                const maxY = containerBottom - containerScrollTop - (targetElement.offsetHeight);
                deltaX = Math.max(minX, Math.min(deltaX, maxX));
                deltaY = Math.max(minY, Math.min(deltaY, maxY));
                // 应用新的位置
                targetElement.style.left = deltaX + 'px';
                targetElement.style.top = deltaY + 'px';
            });
            hammer.on('panend', function (e) {
                console.log(event.current,'event.current')
                // alert(event.current)
                const targetElement = e.target.closest('.gridItem')
                if (event.current>1) {
                    // posX = 0
                    // posY = 0
                    // targetElement.style.left = targetElement.getAttribute('prevLeft')+'px'
                    // targetElement.style.top = targetElement.getAttribute('prevTop')+'px'
                    return
                }
                
            
                
                targetElement.style.zIndex = 0
                const targetRect = targetElement.getBoundingClientRect()
                let maxOverlapArea = 0;
                let maxOverlapIndex = -1;
            
                for (let i = 0,len = lis.current.length; i < len; i++) {
                  const element = lis.current[i];
                  if (element !== targetElement) {
                    const elementRect = element.getBoundingClientRect();
                    const overlapArea = calculateOverlapArea(targetRect, elementRect);
            
                    if (overlapArea > maxOverlapArea) {
                      maxOverlapArea = overlapArea;
                      maxOverlapIndex = i;
                    }
                  }
                }
            
                if (maxOverlapIndex >= 0 && maxOverlapArea >= 500) {
                        const startEl = targetElement.querySelector('img')
                    const endEl = lis.current[maxOverlapIndex].querySelector('img')
                    targetElement.style.left = posX + 'px'
                    targetElement.style.top = posY + 'px'
                    targetElement.setAttribute('prevleft',posX)
                    targetElement.setAttribute('prevtop', posY)
                    const cache = {
                        id: endEl.id,
                        src: endEl.src
                    }
                    endEl.id = startEl.id
                    endEl.src = startEl.src
                    startEl.id = cache.id
                    startEl.src = cache.src
                    
                    
                } else {
                    targetElement.style.left = posX + 'px'
                    targetElement.style.top = posY + 'px'
                    targetElement.setAttribute('prevleft',posX)
                    targetElement.setAttribute('prevtop',posY)
                }
                const imgs = imgBoxRef.current.querySelectorAll('img')
                imgs.forEach(img => {
                    img.classList.remove('disabled')
                    
                })
                isSuccess()
            });
            imgArr.current.push(img)

            // img.draggable = true
            li.appendChild(img)
            lis.current.push(li)
            imgBoxRef.current?.append(li)

        }
        setTimeout(() => {
            const lis = imgBoxRef.current.querySelectorAll('.gridItem')
            const itemWidth = imgArr.current[0].offsetWidth;
            const itemHeight = imgArr.current[0].offsetHeight;
            const containerWidth = imgBoxRef.current.offsetWidth;
            const containerHeight = imgBoxRef.current.offsetHeight;
            const horizontalGap = (containerWidth - itemWidth * numCols) / (numCols - 1);
            const verticalGap = (containerHeight - itemHeight * numRows) / numRows;
            lis.forEach((imgEl, index) => {
                const row = Math.floor(index / 3)
                const col = index % numCols
                const leftPos = col * (itemWidth + horizontalGap);
                const topPos = row * (itemHeight + verticalGap);
                imgEl.style.left = leftPos + 'px';
                imgEl.style.top = topPos + 'px';
                imgEl.setAttribute('prevleft',leftPos)
                imgEl.setAttribute('prevtop',topPos)
                
            })
        }, 10);
        imgBoxRef.current.addEventListener('touchstart',e => {
            // console.log(e)
            event.current = e.touches.length
            console.log(e,'eeeee')
            let item = 0
            

            // e.touches.
            // if (e.target.classList.contains('canvas-img'))

            if (e.touches.length>1) {
                // alert(2)
                // console.log(,'e.touches.item(index).classList')
                
                // randomImg()
                for (let index = 0; index < e.touches.length; index++) {
                    const ele = e.touches[index]
                    // alert(ele)
                    if (ele.classList.contains('canvas-img')) {
                        item+=1
                    }
                    
                }
                if (item>1) {
                    Toast.show('请每次操作一个图片')
                setTimeout(() => {
                    global.location.reload()
                }, 300);
                }
                
                // imgBoxRef.current.classList.contains('disabled')

            } else {
                imgBoxRef.current.classList.remove('disabled')
            }
            
        },true)

    }
    const renderImage = (img,numRows,numCols) => {
        let index = 0
        // console.log(window.innerWidth)
        // console.log()
        
        imgArr.current.sort(() => Math.random() - Math.random())
        // const imgWidth = 372
        // img.width = 310
        // img.height
        
        // debugger
        const ctx = canvasRef.current.getContext('2d')
        const width = img.width;
            const height = img.height;

            const tileWidth = Math.floor(width*2.6 / numCols);
            const tileHeight = Math.floor(height*2.6 / numRows);

            // canvas.width = tileWidth;
            // canvas.height = tileHeight;
        canvasRef.current.width = tileWidth
        canvasRef.current.height = tileHeight

        for (let row = 0; row < numRows; row++) {
            for (let col = 0; col < numCols; col++) {
                ctx.clearRect(0, 0, tileWidth, tileHeight);
                ctx.drawImage(
                    img,
                    col * tileWidth,
                    row * tileHeight,
                    tileWidth,
                    tileHeight,
                    0,
                    0,
                    tileWidth,
                    tileHeight
                );

                // 创建一个新的Image对象，将Canvas中的内容转换为DataURL
                // const tileImg = new Image();
                imgArr.current[index].src = canvasRef.current.toDataURL('image/jpg').replace(/\s/g, "");
                console.log(canvasRef.current.toDataURL('image/jpg').replace(/\s/g, ""))
                imgArr.current[index].id = index
                index++
                // 在这里你可以将tileImg保存到服务器或进行其他操作
                // 例如：saveImageToServer(tileImg, row, col);
            }
        }

        // for (let i = 0; i < 4; i++) {
        //     for (let j = 0; j < 3; j++) {
        //         context.clearRect(0, 0, imgWidth*2, imgWidth*2)
        //         context.drawImage(image, imgWidth * j, imgWidth * i, imgWidth, imgWidth, 0, 0, imgWidth, imgWidth)
        //         imgArr.current[index].src = canvasRef.current.toDataURL('image/jpg').replace(/\s/g, "");;
        //         imgArr.current[index].id = index
        //         index++
        //     }

        // }
    }
    const isSuccess = () => {
        const imgLikeArr = imgBoxRef.current.querySelectorAll('img'),
            imgArr = Array.prototype.slice.call(imgLikeArr)
        let flag = true

        for (let i = 0, len = imgArr.length; i < len; i++) {
            if (imgArr[i].id != i) {
                flag = false;
            }
        }

        if (flag) {
            setTimeout(function () {
                // Toast.show('完成')
                options.onSuccess&&options.onSuccess()
            }, 200);
        }
    }
    const init = async (src = '') => {
       return new Promise((resolve) => {
        const image = new Image()
        image.src = src
        image.width = 310
        image.style.display = 'block'
        image.height = 413.5
        image.setAttribute("crossOrigin", "anonymous");
        imgBoxRef.current.innerHTML = ""
        image.onload = () => {
            
            imgBoxRef.current.append(image)
            setTimeout(() => {
                imgArr.current = []
        lis.current = []
                imgBoxRef.current.innerHTML = ""
                randomImg()
            renderImage(image,4,3)
            resolve(true)
            }, 4000);
            //  dragEvent()
        }
        image.onerror = () => {
            resolve(false)
        }
       })
       
        // image.style.position = 'fixed'
        // image.style.top = '50%'
        // image.style.left = '50%'
        // image.style.transform = 'translate(-50%, -50%)'
        // image.style.zIndex = 99
        // document.body.appendChild(image)
    }


    return {
        init,
        canvasRef,
        imgBoxRef
    }
}